package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.entity.SetmealDish;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/dish")
public class DishController {

    @Autowired
    private DishService dishService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 添加商品
     *
     * @param dishDto
     * @return
     */
    @PostMapping
    public R saveDish(@RequestBody DishDto dishDto) {
        dishService.insert(dishDto);

        //清理某个分类下面的菜品缓存数据
       /* String key = "dish_"+dishDto.getCategoryId()+"_1";
        redisTemplate.delete(key);*/

        //清理所有分类下的菜品缓存
        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);

        return R.success("添加成功");
    }

    /**
     * 分页查询菜品数据
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R queryPage(int page, int pageSize, String name) {
        //设置page对象,设置当前页和每页大小
        IPage<Dish> p = new Page<>(page, pageSize);

        //  IPage<DishDto> dishDtoPage = new Page<>(page, pageSize);

        //封装查询条件like
        LambdaQueryWrapper<Dish> qw = new LambdaQueryWrapper();
        qw.like(StringUtils.isNotEmpty(name), Dish::getName, name);
        //封装排序
        qw.orderByDesc(Dish::getUpdateTime);
        dishService.page(p, qw);

        //获取总条数
        long total = p.getTotal();
        //获得查询列表数据
        List<Dish> records = p.getRecords();
        Map map = new HashMap();
        map.put("total", total);

        // List<DishFlavor> df=new ArrayList<>();
        List<DishDto> dishDtos = records.stream().map((dish -> {
            Long categoryId = dish.getCategoryId();
            Category category = categoryService.getById(categoryId);
            DishDto dishDto = new DishDto();
            if (category != null) {
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }
            BeanUtils.copyProperties(dish, dishDto);
            return dishDto;
        })).collect(Collectors.toList());
        map.put("records", dishDtos);
        return R.success(map);
    }

    /**
     * 修改菜品数据,根据id查询菜品数据
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R getDish(@PathVariable Long id) {
        LambdaQueryWrapper<Dish> qw = new LambdaQueryWrapper();
        qw.eq(StringUtils.isNotEmpty(String.valueOf(id)), Dish::getId, id);
        Dish dish = dishService.getOne(qw);

        DishDto dishDto = new DishDto();
        //将dish菜品赋值拷贝给dishDto对象
        BeanUtils.copyProperties(dish, dishDto);

        LambdaQueryWrapper<DishFlavor> dfqw = new LambdaQueryWrapper();
        dfqw.eq(StringUtils.isNotEmpty(String.valueOf(id)), DishFlavor::getDishId, id);
        List<DishFlavor> list = dishFlavorService.list(dfqw);

        dishDto.setFlavors(list);
        return R.success(dishDto);
    }

    /**
     * 修改菜品
     *
     * @param dishDto
     * @return
     */
    @PutMapping
    public R update(@RequestBody DishDto dishDto) {
        //修改菜品dish表的数据
        dishService.updateById(dishDto);
        //获取菜品id
        Long id = dishDto.getId();

        //删除原有口味数据
        LambdaQueryWrapper<DishFlavor> qw = new LambdaQueryWrapper();
        qw.eq(StringUtils.isNotEmpty(String.valueOf(id)), DishFlavor::getDishId, id);
        dishFlavorService.remove(qw);

        //添加菜品口味数据
        List<DishFlavor> flavors = dishDto.getFlavors();
        flavors = flavors.stream().map(item -> {
            item.setDishId(dishDto.getId());
            return item;
        }).collect(Collectors.toList());

        //批量保存
        dishFlavorService.saveBatch(flavors);

        //清理所有分类下的菜品缓存
        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);

        return R.success("修改成功");
    }

    /**
     * 删除菜品/批量删除菜品
     *
     * @param ids
     * @return
     */
    @DeleteMapping
    public R deleteDish(@RequestParam List<Long> ids) {
        boolean flag = dishService.removeByIds(ids);
        return flag ? R.success("删除成功") : R.error("删除失败");
    }

    /**
     * 起售/停售 批量起售/批量停售
     *
     * @param ids
     * @return
     */
    @PostMapping("/status/{status}")
    public R haltSale(@RequestParam List<Long> ids, @PathVariable Integer status) {
        // int status = 0;
        LambdaUpdateWrapper<Dish> qw = new LambdaUpdateWrapper<>();
        qw.set(Dish::getStatus, status);
        qw.in(Dish::getId, ids);
        boolean flag = dishService.update(qw);
        return flag ? R.success("操作成功") : R.error("操作失败");

    }

    /**
     * 根据分类id查询该分类下的所有菜品集合
     *
     * @param dishDto
     * @return
     */
  /*  @GetMapping("/list")
    public R<List<Dish>> dishList(Dish dish){
        LambdaQueryWrapper<Dish> qw = new LambdaQueryWrapper();
        qw.eq(dish.getCategoryId() != null,Dish::getCategoryId,dish.getCategoryId());
        qw.eq(Dish::getStatus,1);
        //排序条件
        qw.orderByDesc(Dish::getStatus);
        List<Dish> list = dishService.list(qw);
        return R.success(list);
    }*/
    @GetMapping("/list")
    public R<List<DishDto>> dishList(DishDto dishDto) {
        List<DishDto> collect =null;

        //动态构造key
        String key ="dish_" + dishDto.getCategoryId()+"_" + dishDto.getStatus();

        //先从redis中获取缓存数据
        collect = (List<DishDto>) redisTemplate.opsForValue().get(key);
        if(collect!=null){
            return  R.success(collect);
        }

        LambdaQueryWrapper<Dish> qw = new LambdaQueryWrapper();
        qw.eq(dishDto.getCategoryId() != null, Dish::getCategoryId, dishDto.getCategoryId());
        qw.eq(dishDto.getStatus()!=null,Dish::getStatus, dishDto.getStatus());
        //排序条件
        qw.orderByDesc(Dish::getStatus);
        List<Dish> dishList = dishService.list(qw);

        collect = dishList.stream().map((item) -> {
            DishDto dto = new DishDto();
            BeanUtils.copyProperties(item, dto);
            LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq( DishFlavor::getDishId, item.getId());
            List<DishFlavor> list = dishFlavorService.list(queryWrapper);
            dto.setFlavors(list);
            return dto;
        }).collect(Collectors.toList());

        //如果不存在,需要查询数据库,将查询到的菜品数据缓存到redis
        redisTemplate.opsForValue().set(key,collect,60, TimeUnit.MINUTES);
        return R.success(collect);
    }

}
